//
//  YZEMyinfoTableViewController.m
//  yilutongxing
//
//  Created by T&J on 2017/3/23.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import <MJExtension.h>
#import <UIButton+WebCache.h>
#import "UserDefaultsTools.h"
#import "AppDelegate.h"
#import "OperationInfoBean.h"
#import "TimeTools.h"
#import "YZEMyinfoTableViewController.h"
#import "YZEMyBasicinfoViewController.h"
#import "YZEMsgcenterTableViewController.h"
#import "YZEMedicalTableViewController.h"
#import "YZESuifangGanzangTableViewController.h"
#import "YZEGanzangCheckViewController.h"
#import "YZEMySuifangTableViewController.h"

#define URL_GetOperationinfo @"/api/opertion/mine"

@interface YZEMyinfoTableViewController ()<YZEMyBasicinfoValueSetter>
@property (strong, nonatomic) IBOutlet UIButton *btn_shebao;

@property(nonatomic, strong) NSDictionary *unreadDic;
@end

#define AVATAR_WIDTH 100
#define AVATAR_HEIGHT 100
#define MY_HEADER_HEIGHT 200 //头部高度
#define MY_PAD_TOP 30 //头部内容距离屏幕顶部高度

#define URL_GetUnreadTotal @"/api/message-boxes/mine"

@implementation YZEMyinfoTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    self.tableView.mj_header = [RefershHelper headerWithRefreshingBlock:^{
        [self getMessageCount];
        [self getOperationInfo];
        [self.tableView.mj_header endRefreshing];
    }];

    //网络请求消息未读数
    [self getMessageCount];
}

-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = NO;
    
    [[YZEModel sharedInstace] requestUserInfoWithDelegate:self requestTag:666];
    
    //网络请求消息未读数
    [self getMessageCount];
}
-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//warning Incomplete implementation, return the number of sections
    return 3;
}

//自定义第一节header
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section!=0) {
        return nil;
    }
    static NSString *headerSectionID = @"cityHeaderSectionID";
    UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerSectionID];
    
    
    
    if (headerView==nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:headerSectionID];
        headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, MY_HEADER_HEIGHT);
        headerView.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"我的背景"]];
        //消息图标
        m_btn_msg = [UIButton buttonWithType:UIButtonTypeSystem];
        m_btn_msg.frame = CGRectMake(SCREEN_WIDTH-40, 30, 26, 20);
        [m_btn_msg setBackgroundImage:[UIImage imageNamed:@"信息"] forState:UIControlStateNormal];
        [headerView addSubview:m_btn_msg];
        //消息bagage
        m_btn_badagge = [[UIButton alloc]initWithFrame:CGRectMake(18, -5, 16, 16)];
        [m_btn_badagge setBackgroundImage:[UIImage imageNamed:@"提醒"] forState:UIControlStateNormal];
        m_btn_badagge.layer.cornerRadius = 6;
        m_btn_badagge.layer.masksToBounds = 6;
        [m_btn_badagge setTitleColor:WHITE_COLOR forState:UIControlStateNormal];
        [m_btn_badagge.titleLabel setFont:[UIFont systemFontOfSize:10]];
        m_btn_badagge.hidden = YES;
        //[m_btn_badagge setTitle:@"83" forState:UIControlStateNormal];
        [m_btn_msg addSubview:m_btn_badagge];

        //头像
        m_btn_avatar = [[UIImageView alloc]init];
        m_btn_avatar.frame = CGRectMake((SCREEN_WIDTH-AVATAR_WIDTH)/2, MY_PAD_TOP, AVATAR_WIDTH, AVATAR_HEIGHT);
        m_btn_avatar.layer.cornerRadius = AVATAR_WIDTH/2;
        m_btn_avatar.layer.masksToBounds = AVATAR_WIDTH/2;
         [m_btn_avatar sd_setImageWithURL:[NSURL URLWithString:self.userInfo.avatar] placeholderImage:[UIImage imageNamed:@"头像"]];
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onAvaNameClick)];
        [m_btn_avatar addGestureRecognizer:tap];
        m_btn_avatar.userInteractionEnabled=YES;
        [headerView addSubview:m_btn_avatar];
        [headerView addSubview:m_btn_avatar];
        //姓名按钮
        m_btn_name = [UIButton buttonWithType:UIButtonTypeSystem];
        m_btn_name.frame = CGRectMake((SCREEN_WIDTH-100)/2, (MY_PAD_TOP+AVATAR_HEIGHT)+6, 100, 20);
        NSDictionary *atr =[NSDictionary dictionaryWithObjectsAndKeys:WHITE_COLOR, NSForegroundColorAttributeName, [UIFont systemFontOfSize:18.0f], NSFontAttributeName, nil];
        NSAttributedString *atrTitle = [[NSAttributedString alloc]initWithString:self.userInfo.user.firstName
                                                                      attributes:atr];
        [m_btn_name setAttributedTitle:atrTitle forState:UIControlStateNormal];
        [headerView addSubview:m_btn_name];
        //手术时长
        l_optime = [[UILabel alloc]initWithFrame:CGRectMake(0, m_btn_name.frame.origin.y + m_btn_name.frame.size.height + 6, SCREEN_WIDTH, 21)];
        l_optime.textAlignment = NSTextAlignmentCenter;
        [l_optime setTextColor:COLOR(230, 230, 230)];
        [headerView addSubview:l_optime];
        [self getOperationInfo];
        //事件注册
        [m_btn_name addTarget:self action:@selector(onAvaNameClick) forControlEvents:UIControlEventTouchUpInside];
        [m_btn_msg addTarget:self action:@selector(onMsgClick:) forControlEvents:UIControlEventTouchUpInside];
        [m_btn_badagge addTarget:self action:@selector(onMsgClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.btn_shebao addTarget:self action:@selector(onMyshebao:) forControlEvents:UIControlEventTouchUpInside];//我的社保按钮
    }
    return headerView;
}

//设置状态栏白色
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

//返回header高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section!=0) {
        return 10;
    }
    return MY_HEADER_HEIGHT;
}

#pragma mark - 数据请求
//获取未读消息数
- (void)getMessageCount{
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_GetUnreadTotal]
                                      parameters:nil
                                        delegate:self
                                      requestTag:1
                                    successBlock:^(id responseObject)
     {
         self.unreadDic = responseObject;
         int total = 0;
         for (NSDictionary *model in (NSArray*)responseObject) {
             total += [((NSNumber*)model[@"unreadCount"]) intValue];
         }
         [m_btn_badagge setTitle:[NSString stringWithFormat:@"%d",total] forState:UIControlStateNormal];
         m_btn_badagge.hidden = total==0;
     }];
}
//获取手术信息
- (void)getOperationInfo{
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_GetOperationinfo] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        OperationInfoBean *opinfo = [OperationInfoBean mj_objectWithKeyValues:responseObject];
        l_optime.text = [NSString stringWithFormat:@"术后%@", [TimeTools getTimeGapHumanDescForDate:opinfo.opTime]];
    }];
}

//消息按钮点击响应
- (void)onMsgClick:(UIButton*)sender{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"userinfo" bundle:nil];
    YZEMsgcenterTableViewController *myinfoView = [sb instantiateViewControllerWithIdentifier:@"msgcenterVC"];
    myinfoView.unreadArr = self.unreadDic;
    [self.navigationController pushViewController:myinfoView animated:YES];
}

//头像和名字点击响应
- (void)onAvaNameClick{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"userinfo" bundle:nil];
    YZEMyBasicinfoViewController *myinfoView = [sb instantiateViewControllerWithIdentifier:@"infoVC"];
    myinfoView.delegate = self;
    [self.navigationController pushViewController:myinfoView animated:YES];
}

//我是社保点击响应
- (void)onMyshebao:(UIButton *)sender{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"userinfo" bundle:nil];
    YZEMedicalTableViewController *medicalView = [sb instantiateViewControllerWithIdentifier:@"shebaoVC"];
    medicalView.medical_type = self.userInfo.medical;
    medicalView.lastView = self;
    
    [self.navigationController pushViewController:medicalView animated:YES];
}

//登出按钮响应
- (IBAction)signoutClick:(UIButton *)sender {
    [UserDefaultsTools deleteUserDefaultsForKey:TOKEN_KEY];
    AppDelegate *app=(AppDelegate*)[UIApplication sharedApplication].delegate;
    [app initLoginController];
}

//设置医保类型
-(void)setMedical:(NSString *)medical{
    [self.userInfo setValue:medical forKey:@"medical"];
    [UserDefaultsTools saveUserDefaultsObject:_userInfo.mj_keyValues forKey:USERINFO_KEY];
}

#pragma mark 基本资料设置代理回调
- (void)backHeadImage:(UIImage *)img{
    [m_btn_avatar setImage:img];
}

#pragma mark - 乱七八糟的网络代理回调
- (void)OnSuccess:responseObject requestTag:(int)tag{
    if (tag==666) {
        NSDictionary *dic=[UserDefaultsTools getUserDefaultsForKey:USERINFO_KEY];
        self.userInfo=[RPUserInfoBean mj_objectWithKeyValues:dic];
        NSDictionary *atr =[NSDictionary dictionaryWithObjectsAndKeys:WHITE_COLOR, NSForegroundColorAttributeName, [UIFont systemFontOfSize:18.0f], NSFontAttributeName, nil];
        NSAttributedString *atrTitle = [[NSAttributedString alloc]initWithString:self.userInfo.user.firstName
                                                                      attributes:atr];
        [m_btn_name setAttributedTitle:atrTitle forState:UIControlStateNormal];
        [m_btn_avatar sd_setImageWithURL:[NSURL URLWithString:self.userInfo.avatar] placeholderImage:[UIImage imageNamed:@"头像"]];
    }
}

@end
